package com.intmall.demo.service.impl;

import com.intmall.demo.entity.User;
import com.intmall.demo.mapper.UserMapper;
import com.intmall.demo.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author intmall
 * @since 2022-03-02
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    public static final String CACHE_KEY_UERR = "user:";

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public void addUser(User user) {
        boolean result = this.save(user);
        if (result) {
            user = this.getById(user.getId());
            log.info("保存成功：{}", user);
            String key = CACHE_KEY_UERR + user.getId();
            redisTemplate.opsForValue().set(key, user);
        }
    }

    @Override
    public User findUserById(Long id) {
        User user = null;
        String key = CACHE_KEY_UERR + id;
        user = (User) redisTemplate.opsForValue().get(key);
        if (user == null) {
            user = this.getById(id);
            if (user == null) {
                return null;
            }
            redisTemplate.opsForValue().set(key, user);
        }
        return user;
    }
}
